/*
 * Copyright (c) 2009, Hamish Morgan. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the University of Sussex nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package locusts.common.vibro;

import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.mina.common.IoSession;
import org.apache.mina.handler.demux.MessageHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Create new new serial connection to the vibro tactile device and send
 * updates.
 *
 * @author Hamish Morgan
 */
public class VTMessageHandler implements MessageHandler<VTMessage> {

    private static final String PORT_NAME =
            "/dev/tty.usbserial-A7006SaH";
    private static final int OPEN_TIMEOUT = 2000;
    private static final String APP_NAME = VTMessageHandler.class.getName();
    private static final int BAUD_RATE = 9600;
    private static final int DATABITS = SerialPort.DATABITS_8;
    private static final int STOPBITS = SerialPort.STOPBITS_1;
    private static final int PARITY = SerialPort.PARITY_NONE;
    //
    private static final Logger LOG = LoggerFactory.getLogger(
            VTMessageHandler.class);
    private CommPortIdentifier portId;
    private SerialPort port;
    private InputStream in;
    private OutputStream out;
    private VTMessage vtdata;

    public VTMessageHandler() throws Exception {
        vtdata = null;
        init();
    }

    private void init() {

        if (!portExists(PORT_NAME)) {
            System.out.println("VibroTactile USB/Serial port not found.");
            return;
        }

        try {
            portId = CommPortIdentifier.getPortIdentifier(PORT_NAME);

            if (portId.isCurrentlyOwned()) {
                LOG.error(
                        "The specified port ({}) is currently owned by {}.",
                        new Object[]{portId.getName(),
                            portId.getCurrentOwner()});
                return;
            }

            if (portId.getPortType() != portId.PORT_SERIAL) {
                LOG.error("The specified name is not a serial port.");
                return;
            }

            port = (SerialPort) portId.open(APP_NAME, OPEN_TIMEOUT);

            port.setSerialPortParams(BAUD_RATE, DATABITS, STOPBITS, PARITY);

            in = port.getInputStream();
            out = port.getOutputStream();

            (new Thread(new VTIOThread())).start();

        } catch (NoSuchPortException e) {
            LOG.warn("Serial Port does not exist.", e);
        } catch (PortInUseException e) {
            LOG.error("The specified port is currently in use.");
        } catch (UnsupportedCommOperationException e) {
            LOG.error(null, e);
        } catch (IOException e) {
            LOG.error(null, e);
        }

    }

    @Override
    protected void finalize() throws Throwable {

        int n = vtdata.getBytes().array().length;
        for (int i = 0; i < n; i++)
            out.write(0);
        out.write('#');
        out.close();
        in.close();
        super.finalize();
        port.close();

    }

    private class VTIOThread implements Runnable {

        public void run() {

            try {
                while (vtdata == null) {
                    Thread.sleep(10);
                }
                while (true) {

                    int b;
                    while ((b = in.read()) != '\r') {
                        // NB: It always send a  '0' byte here but i don't knwo why.
                    }
                    out.write(vtdata.getBytes().array());
                    out.write('#');

                }
            } catch (IOException ex) {
                LOG.error(null, ex);
            } catch (InterruptedException ex) {
                LOG.error(null, ex);
            }
        }
    }

    private static boolean portExists(String name) {
        @SuppressWarnings("unchecked")
        final java.util.Enumeration<CommPortIdentifier> portEnum =
                CommPortIdentifier.getPortIdentifiers();
        while (portEnum.hasMoreElements()) {
            final CommPortIdentifier cpid = portEnum.nextElement();
            if (cpid.getName().equals(name))
                return true;
        }

        return false;
    }

    public void messageReceived(IoSession session, VTMessage message) throws
            Exception {
        vtdata = message.transpose();//.minValue(200);
//        System.out.println("Recieved VTMessage: ");
//        System.out.println(vtdata);
    }
}
